package com.starnet.yarnmonitor.security.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.starnet.yarnmonitor.yarn.handler.ApiException;
import com.starnet.yarnmonitor.security.custom.JwtAuthenticationProvider;
import com.starnet.yarnmonitor.security.entity.LoginUser;
import com.starnet.yarnmonitor.security.service.LoginService;
import com.starnet.yarnmonitor.security.utils.JwtUtil;
import com.starnet.yarnmonitor.security.utils.RedisCache;
import com.starnet.yarnmonitor.security.vo.param.LoginParam;
import com.starnet.yarnmonitor.yarn.vo.result.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
@Service
public class LoginServiceImpl implements LoginService {
   @Autowired
    AuthenticationManager authenticationManager;
   @Autowired
   PasswordEncoder passwordEncoder;

    @Resource
    JwtAuthenticationProvider authenticationProvider;

   @Resource
    RedisCache redisCache;



    @Override
    public Result login(LoginParam loginParam) {
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken=new UsernamePasswordAuthenticationToken(loginParam.getUsername(),loginParam.getPassword());
        Authentication authentication = authenticationManager.authenticate(usernamePasswordAuthenticationToken);
        if (authentication==null){
            throw new ApiException("登录失败");

        }
        LoginUser userInDB= (LoginUser) authentication.getPrincipal();
        //传入的密码
        String inputPassword=loginParam.getPassword();
        //数据库中的密码
        String dBPassword = userInDB.getPassword();
        boolean isMatch = passwordEncoder.matches(inputPassword,dBPassword);
        if (!isMatch){
            throw new RuntimeException("密码不正确");
        }

        String userId=userInDB.getUser().getId().toString();
        String jwt = JwtUtil.createJWT(userId);
        Map<String,String> map=new HashMap<>();
        map.put("token",jwt);
        //存入redis
        redisCache.setCacheObject("login:"+userId, JSONObject.toJSONString(userInDB));
        return Result.success();
    }

    @Override
    public Result logout() {
        UsernamePasswordAuthenticationToken authenticationToken = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext();
        LoginUser loginUser = (LoginUser) authenticationToken.getPrincipal();
        //删除redis中的id
        Integer id = loginUser.getUser().getId();
        redisCache.deleteObject("login:"+id);
        return Result.success("注销成功");
    }
}
